package com.example.practice;


import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;


/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment_3 extends Fragment implements View.OnClickListener {


    private TextView uText3;
    private Spinner spinner3;
    private EditText cText3;
    private Button qx3;
    private Button cz3;
    private View view;
    private String ye;
    private List<Car2Users> listc;
    private int j;
    public Fragment_3() {
        // Required empty public constructor
    }

    private interface Blogclient {
        @POST("charge")
        Call<ResponseBody> Blog(@Body RequestBody str);
    }
    private interface Blogsever{
        @GET("carlist")
        Call<ResponseBody> getBlog();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_3, container, false);
        initView();
        initData();
        cText3.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                    cText3.setText("");
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.toString().startsWith("")) {
                    cText3.setText("222222");
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().startsWith("0")) {
                    cText3.setText("");
                }
            }
        });
        return view;
    }

    private void initData() {
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Blogsever blogsever = retrofit1.create(Blogsever.class);
        Call<ResponseBody> blog = blogsever.getBlog();
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Gson gson = new Gson();
                    Car2Users carUsers = gson.fromJson(string, Car2Users.class);
                    listc = new ArrayList<>();
                    listc.add(carUsers);
                    uText3.setText(listc.get(0).getData().get(0).getAmount()+"元");
                    spinner();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    private void spinner() {
        final String[] arr = getResources().getStringArray(R.array.language);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (getActivity(),android.R.layout.simple_spinner_dropdown_item, arr);
        spinner3.setAdapter(adapter);
        spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                j=i;
                ye=listc.get(0).getData().get(i).getAmount()+"元";
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.qx3:
                uText3.setText(ye);
                break;
            case R.id.cz3:
                final String s = cText3.getText().toString();
                Retrofit retrofit1 = new Retrofit.Builder()
                        .baseUrl("http://hh1.me:5001/")
                        .build();
                Blogclient blogsever = retrofit1.create(Blogclient.class);
                Map<String,String> map = new HashMap<>();
                map.put("who",listc.get(0).getData().get(j).getWho());
                map.put("carno",listc.get(0).getData().get(j).getCarno());
                map.put("amount",s);
                Gson gson = new Gson();
                String s1 = gson.toJson(map);
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),s1);
                Call<ResponseBody> blog = blogsever.Blog(requestBody);
                blog.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        initData();
                        Toast.makeText(getContext(), "充值成功", Toast.LENGTH_SHORT).show();
                        SqliteUsers sUsers = new SqliteUsers(getContext());
                        SQLiteDatabase db = sUsers.getReadableDatabase();
                        ContentValues values = new ContentValues();
                        values.put("charge_user", listc.get(0).getData().get(j).getWho());
                        values.put("charge_amount", s);
                        values.put("charge_carno",j+1);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                        Date date = new Date(System.currentTimeMillis());
                        values.put("charge_data",simpleDateFormat.format(date));
                        db.insert("charge", null, values);
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(getContext(), "充值失败", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
        }
    }
    private void initView() {
        uText3=view.findViewById(R.id.uText3);
        spinner3=view.findViewById(R.id.spinner3);
        cText3=view.findViewById(R.id.cText3);
        qx3=view.findViewById(R.id.qx3);
        qx3.setOnClickListener(this);
        cz3=view.findViewById(R.id.cz3);
        cz3.setOnClickListener(this);
    }
}
